#ifndef								__PACKET_H__
#	define							__PACKET_H__

#	include							"byte.h"
#	include							<iostream>
#	include							<vector>

class								Packet
{
public:
	Packet(){_content = 0;};
	~Packet(){};

private:
	std::vector<byte>				*_content;
	std::vector<byte>::iterator		_it;
	size_t							_current;
	std::string						_from;
	unsigned int						_id;
public:
	void						destroy()
	{
		delete _content;
	}

	template<typename T>
	T 							*getData(size_t size)
	{
		byte				*data = new byte[sizeof(T) * size];
		size_t				cnt = 0;
		size_t				total = _content->size();

		while (_current < total && cnt < sizeof(T) * size)
		{
			data[cnt] = (*_content)[_current];
			_current++;
			cnt++;
		}

		if (cnt != sizeof(T) * size)
		{
			std::cout << "[CRITICAL] error on packet : can't read more data" << std::endl;
			return NULL;
		}
		return (T*)data;
	}

	template<typename T>
	void							pushData(T *data, size_t size)
	{
		byte				*input = (byte*)data;

		for (size_t cnt = 0; cnt < size * sizeof(T); ++cnt)
			_content->push_back(input[cnt]);
	}

	template<typename T>
	void							pushData(T *data)
	{
		byte				*input = (byte*)data;

		for (size_t cnt = 0; cnt < sizeof(T); ++cnt)
			_content->push_back(input[cnt]);
	}


	size_t							size() const
	{
		return _content->size();
	}

	void							setData(std::vector<byte> *data)
	{
		_content = data;
		_current = 0;
	}

	byte							*toUdpNetworkPacket()
	{
	  if (_content->size() > 0)
	    {
	      std::vector<byte>::iterator it = _content->begin();
	      byte				*msg = new byte[_content->size()];
	      size_t			cnt = 0;
		  unsigned int		maxsize = _content->size();

			 while (cnt < maxsize)
			{
			  msg[cnt] = (*_content)[cnt];
			  cnt++;
			}
		  return msg;
		}
	  std::cout << "[CRITICAL] error in toNetworkPacket : packet is too small" << std::endl;
	  return NULL;
	}

	byte							*toTcpNetworkPacket()
	{
		if (_content->size() >= 2)
		{
			unsigned short		size = _content->size();
			std::vector<byte>::iterator it = _content->begin();
			byte				*msg = new byte[size + sizeof(size)];
			size_t				cnt = 2;

			msg[0] =  ((byte*)&size)[0];
			msg[1] =  ((byte*)&size)[1];
			while (it != _content->end())
			{
				msg[cnt] = *it;
				cnt++;
				it++;
			}
			return msg;
		}
		std::cout << "[CRITICAL] error in toNetworkPacket : packet is too small" << std::endl;
		return NULL;
	}

	void							init()
	{
		if (_content)
			delete _content;
		_content = new std::vector<byte>;
	}

	void							setFrom(std::string from)
	{
		_from = from;
	}

	void							setFrom(unsigned int id)
	{
		_id = id;
	}

	std::string &					getFrom()
	{
		return _from;
	}

	unsigned int					getId()
	{
	  return _id;
	}
};

#endif								// ! __PACKET_H__
